import { useModel } from "umi";
import { useReactive } from "ahooks";
import { useEffect } from "react";

const useAllApplications = () => {
    const { remoteData } = useModel("global");

    const state = useReactive({
        loading: false,
        pageSize: 20,
        page: 1,
        applications: [],
        totalCount: 0,
    });

    const loadAllApplications = async () => {
        state.loading = true;
        let res = await remoteData({
            object: "bnt-application-resource-center-service",
            serviceName: "/developer/application/getAllByPage",
            params: {
                limit: state.pageSize,
                offset: (state.page - 1) * state.pageSize || 0,
                order: [["appName", "ASC"]],
            },
        });
        if (res) {
            state.applications = res.applications || [];
            state.totalCount = res.totalCount || 0;
        }
        state.loading = false;
    };

    useEffect(() => {
        loadAllApplications();
    }, [state.page]);

    const setPage = (page) => (state.page = page);

    return { ...state, loadAllApplications, setPage };
};

export default useAllApplications;
